package org.nf.web.param;

import org.nf.web.annotation.RequestMapping;
import org.nf.web.annotation.RequestParam;
import org.nf.web.common.TypeConverter;
import org.nf.web.servlet.MethodArgumentsResolver;
import org.nf.web.servlet.ServletApi;

import java.lang.reflect.Parameter;
import java.util.ServiceLoader;

/**
 * @Author czl
 * @Date 2024-05-17
 */
public class RequestParamMethodArgumentResolver implements MethodArgumentsResolver {

    /**
     * 初始化类型转换SPI
     */
    private static final ServiceLoader<TypeConverter> LOADER = ServiceLoader.load(TypeConverter.class);

    @Override
    public boolean supports(Parameter parameter) {
        return parameter.isAnnotationPresent(RequestParam.class);
    }

    @Override
    public Object resolve(Parameter parameter, ServletApi servletApi) {
        //获取注解的参数值
        String name = parameter.getAnnotation(RequestParam.class).value();
        //根据参数值从请求对象中获取请求的数据
        String value = servletApi.request().getParameter(name);
        //针对不同的参数类型进行类型转换
        Object obj = null;
        for(TypeConverter converter : LOADER) {
            if(converter.supports(parameter.getType())) {
                obj = converter.convert(value);
                break;
            }
        }
        if(parameter.getType().isPrimitive() && obj == null) {
            throw new RuntimeException("Null value not set " + parameter.getType() + ".");
        }
        return obj;
    }
}
